/***********************************************************************************
Copy right:	    hqyj Tech.
Author:         jiaoyue
Date:           2023.07.01
Description:    http请求处理
***********************************************************************************/

#include "shmem.h"
#include "msg_queue_peer.h"
#include "custom_handle.h"
#include "cJSON.h"

#define KB 1024
#define HTML_SIZE (64 * KB)

// 普通的文本回复需要增加html头部
#define HTML_HEAD "Content-Type: text/html\r\n" \
                  "Connection: close\r\n"

static struct shm_param para;
char mb_slave_ip[64] = {}; // 用于存储modbusslave的ip地址
int mb_slave_port = 0;     // 用于存储modbusslave的端口号
uint8_t coils[3] = {};     // 用于存储线圈状态
uint16_t inputs[6] = {};   // 用于存储保持寄存器 //用于存储共享内存参数

// static int handle_login(int sock, const char *input)
// {
//     char reply_buf[HTML_SIZE] = {0};
//     char *uname = strstr(input, "username=");
//     uname += strlen("username=");
//     char *p = strstr(input, "password");
//     *(p - 1) = '\0';
//     printf("username = %s\n", uname);

//     char *passwd = p + strlen("password=");
//     printf("passwd = %s\n", passwd);

//     if (strcmp(uname, "admin") == 0 && strcmp(passwd, "admin") == 0)
//     {
//         sprintf(reply_buf, "<script>localStorage.setItem('usr_user_name', '%s');</script>", uname);
//         strcat(reply_buf, "<script>window.location.href = '/index.html';</script>");
//         send(sock, reply_buf, strlen(reply_buf), 0);
//     }
//     else
//     {
//         printf("web login failed\n");

//         //"用户名或密码错误"提示，chrome浏览器直接输送utf-8字符流乱码，没有找到太好解决方案，先过渡
//         char out[128] = {0xd3, 0xc3, 0xbb, 0xa7, 0xc3, 0xfb, 0xbb, 0xf2, 0xc3, 0xdc, 0xc2, 0xeb, 0xb4, 0xed, 0xce, 0xf3};
//         sprintf(reply_buf, "<script charset='gb2312'>alert('%s');</script>", out);
//         strcat(reply_buf, "<script>window.location.href = '/login.html';</script>");
//         send(sock, reply_buf, strlen(reply_buf), 0);
//     }

//     return 0;
// }
static int handle_get(int sock, const char *input)
{
    int ret = -1;
    ret = shm_init(&para, "shm_test", 1024);
    if (ret < 0)
    {
        perror("shm_init error");
        return -1;
    }
    // 获取共享内存地址
    void *node_p = shm_getaddr(&para);
    if (node_p == NULL)
    {
        perror("shm_getaddr error");
        return -1;
    }
    // total指向共享内存中数据节点总个数
    total = (int *)node_p;
    // node_arr指向共享内存中节点缓存数组头
    node_arr = (std_node *)(node_p + sizeof(int));
    char *json_response;
    *total = 10;

    cJSON *root = cJSON_CreateObject();

    cJSON *item = cJSON_CreateNumber(10);

    // 把item添加到root对象上
    cJSON_AddItemToObject(root, "type", item);
    // 创建一个json数组
    cJSON *data_array = cJSON_CreateArray();

    cJSON_AddItemToObject(root, "data", data_array);
    if (NULL == data_array)
    {
        printf("create err\n");
        return -1;
    }
    for (int i = 0; i < 10; i++)
    {

        cJSON *point_obj = cJSON_CreateObject();
        cJSON_AddNumberToObject(point_obj, "key", node_arr[i].key);
        cJSON_AddNumberToObject(point_obj, "val", node_arr[i].new_val.f_val);
        cJSON_AddItemToArray(data_array, point_obj);
    }
    // 把上面的树转换成字符串
    //  char *str = cJSON_Print(root);
    json_response = cJSON_PrintUnformatted(root);
    if (NULL == json_response)
    {
        printf("print err\n");
        return -1;
    }
    printf("json_response = %s\n", json_response);
    send(sock, json_response, strlen(json_response), 0);
    cJSON_Delete(root);

    // 释放内存
    free(json_response);
    json_response = NULL;
}

// web端请求 控制设备为次要功能
static int handle_set(int sock, const char *input, cJSON *root)
{
    // 提取root中的key和state
    cJSON *key_item = cJSON_GetObjectItem(root, "key");
    cJSON *state_item = cJSON_GetObjectItem(root, "state");
    int key = key_item->valueint;
    int state = state_item->valueint;
    printf("key = %d, state = %d\n", key, state);
    msgqueue msgval;
    if (key ==303)
    {
        msgval.mtype = 1;
        if(state == 1)
        {
            strcpy(msgval.mdata, "FAN_ON");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue FAN_ON\n");
        }
        else if(state == 0)
        {
            strcpy(msgval.mdata, "FAN_OFF");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue FAN_OFF\n");
        }
    }
    else if(key == 304)
    {
        msgval.mtype =1;
        if(state == 1)
        {
            strcpy(msgval.mdata, "BUZZER_ON");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue %s\n",msgval.mdata);
        }
        else if(state == 0)
        {
            strcpy(msgval.mdata, "BUZZER_OFF");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue %s\n",msgval.mdata);
        }
    }
    else if(key == 105)
    {
        msgval.mtype =2;
        if(state == 1)
        {
            strcpy(msgval.mdata, "valve=1");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue %s\n",msgval.mdata);
        }
        else if(state == 0)
        {
            strcpy(msgval.mdata, "valve=0");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue %s\n",msgval.mdata);
        }
    }
    else if(key == 106)
    {
        msgval.mtype =2;
        if(state == 1)
        {
            strcpy(msgval.mdata, "clean=1");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue %s\n",msgval.mdata);
        }
        else if(state == 0)
        {
            strcpy(msgval.mdata, "clean=0");
            msg_queue_send("topic", &msgval, sizeof(msgval), 0);
            printf("send msg_queue %s\n",msgval.mdata);
        }
    }
    memset(&msgval, 0, sizeof(msgval));
    return 0;
}

/**
 * @brief 处理自定义请求，在这里添加进程通信
 * @param input
 * @return
 */
int parse_and_process(int sock, const char *query_string, const char *input)
{
    // query_string不一定能用的到

    // 先处理登录操作
    // if (strstr(input, "username=") && strstr(input, "password="))
    // {
    //     return handle_login(sock, input);
    // }
    // if (strstr(input, "getdata"))
    // {
    //     return handle_get(sock, input);
    // }
    // else if (strstr(input, "toggle"))
    // {
    //     return handle_toggle(sock, input);
    // }
    // 剩下的都是json请求，这个和协议有关了

        // 解析JSON数据
        cJSON *root = cJSON_Parse(input);
        // 提取数据点的type值
        cJSON *type_item = cJSON_GetObjectItem(root, "type");
        // 判断type_item的值是1还是2，1表示获取数据，2表示控制设备
        if (type_item->valueint == 1)
        {
            return handle_get(sock, input);
        }
        else if (type_item->valueint == 2)
        {
            // 提取数据点的key值
            return handle_set(sock, input, root);
            // 提取数据点的state值
        }

        // 构建要回复的JSON数据
        // const char *json_response = "{\"message\": \"Hello, client!\"}";

        // // 发送HTTP响应给客户端
        // send(sock, json_response, strlen(json_response), 0);


    return 0;
}
